package com.data.modules.system.util;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @ClassName OCRUtil
 * @Description:类描述
 * @Author chj
 * @Date 2022/4/11
 * @Version V1.0
 **/
@Slf4j
public class OCRUtil {

    /**
     * 识别图片信息
     * @param img
     * @return
     */
    public static String getImageMessage(BufferedImage img, String language,String url){
        String result="end";
        try{
            ITesseract instance = new Tesseract();
            String osName = System.getProperties().getProperty("os.name");
            File tessDataFolder = new File(url);
           /* File tessDataFolder = null;
            if(osName.toLowerCase().contains("windows")){

                //tessDataFolder = LoadLibs.extractTessResources("tessdata");
                tessDataFolder = new File(System.getProperty("user.dir"),"\\boot-module-system\\src\\main\\resources\\conf\\tessdata");
            }else{
                tessDataFolder = new File(System.getProperty("user.dir"),"lngData");
            }*/

            log.info("==tessdata=="+tessDataFolder.getAbsolutePath());
            String path = tessDataFolder.getAbsolutePath();
            instance.setLanguage(language);
            instance.setDatapath(tessDataFolder.getAbsolutePath());
            result = instance.doOCR(img);
        }catch(Exception e){
            log.error("==getImageMessage=",e.getMessage(),e);
        }
        return result;
    }

    /**
     * 读取图片为灰度图
     *
     * @param imagePath 图片绝对路径
     * @return
     * @throws IOException
     */
    public static BufferedImage readAsGrayImage(String imagePath) throws IOException {
        BufferedImage src = ImageIO.read(new File(imagePath));  //BufferedImage 类的图片资源
        BufferedImage grayImage = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        for (int i = 0; i < src.getWidth(); i++) {
            for (int j = 0; j < src.getHeight(); j++) {
                int rgb = grayImage.getRGB(i, j);
                grayImage.setRGB(i, j, rgb);
            }
        }
        return grayImage;
    }

}
